<template>
  <div>
    <PageDialog
      :title="dialogInfo.title"
      v-model:visible="shows"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="layui-row">
        <div class="select-depot-storage layui-col-md6">
          <!-- 条件栏 -->
          <div class="filter-wrapper flex-end">
            <NewPageFilter
              :filter-btn="leftFilterInfo.btnList"
              v-model:query="leftFilterInfo.query"
              :filter-list="leftFilterInfo.list"
            >
              <template v-slot:filter-btn>
                <el-button
                  :disabled="!leftTableInfo.selections.length"
                  @click="removeRight"
                  >右移</el-button
                >
              </template>
            </NewPageFilter>
          </div>
          <DialogTable
            :refresh="leftTableInfo.refresh"
            :init-curpage="leftTableInfo.initCurpage"
            v-model:data="leftTableInfo.data"
            :api="leftTableInfo.api"
            ref="productTable"
            :pager="false"
            :reserveSelection="true"
            :listenHeight="false"
            v-model:query="leftFilterInfo.query"
            :field-list="leftTableInfo.fieldList"
            :highlight-row="false"
            :check-box="true"
            @handleEvent="leftHandleEvent"
          >
          </DialogTable>
        </div>
        <div
          class="select-depot-storage layui-col-md6"
          style="padding-left: 20px"
        >
          <!-- 条件栏 -->
          <NewPageFilter
            v-model:query="filterInfo.query"
            :filter-list="filterInfo.list"
            :filter-btn="filterInfo.btnList"
          >
            <template v-slot:filter-btn>
              <el-button
                :disabled="!tableInfo.selections.length"
                @click="removeLeft"
                >左移</el-button
              >
            </template>
          </NewPageFilter>
          <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
            <DialogTable
              ref="table"
              :refresh="tableInfo.refresh"
              :init-curpage="tableInfo.initCurpage"
              v-model:data="tableInfo.data"
              :api="tableInfo.api"
              :listen-height="false"
              :reserveSelection="true"
              :pager="false"
              v-model:query="filterInfo.query"
              :field-list="tableInfo.fieldList"
              :handle="tableInfo.handle"
              :highlight-row="highlightRow"
              :check-box="checkBox"
              @handleEvent="handleEvent"
            >
              <template v-slot:col-calcQty="scope">
                <el-form-item
                  @click.stop.native=""
                  :prop="`data.${scope.$index}.calcQty`"
                  :rules="
                    scope.$index >= 0
                      ? [
                          {
                            validator: $validate.numberNotZero,
                            trigger: ['blur', 'change'],
                          },
                        ]
                      : []
                  "
                >
                  <el-input-number
                    v-model="scope.row.calcQty"
                    :precision="
                      $store.state.permission.systemConfig.qty_show_precision
                    "
                    :max="
                      scope.row.availableQty > 0 ? scope.row.availableQty : 0
                    "
                    controls-position="right"
                    :min="
                      scope.row.availableQty < 0 ? scope.row.availableQty : 0
                    "
                    @change="changeNum($event, scope.row, `calcQty`)"
                  ></el-input-number>
                </el-form-item>
              </template>
            </DialogTable>
          </el-form>
        </div>
      </div>
    </PageDialog>
  </div>
</template>

<script setup name="pendReceiptOrderIndividual">
import { getPendReceiptOrderSelectAll } from '@/api/receipt'

const { proxy } = getCurrentInstance()
const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: false,
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  showDialog: {
    type: Boolean,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  api: {
    type: Function,
    default: getPendReceiptOrderSelectAll,
  },
  selectData: {
    type: Object,
    default: function () {
      return {}
    },
  },
  idNotIn: {
    type: String,
    default: '',
  },
})
const leftFilterInfo = ref({
  query: {
    ...props.query,
    idNotIn: props.idNotIn,
    sort: 'create_time desc',
    receiptSourceType: 1,
  },
  btnList: [{ type: 'slot', value: 'btn' }],
})
// 表格相关
const leftTableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  height: '70%',
  data: [],
  selections: [],
  fieldList: [
    { label: '结算单号', value: 'orderNo' },
    { label: '产品名称', value: 'commonName' },
    { label: '批号', value: 'batchNumber' },
    { label: '产品类型', value: 'productTypeValue' },
    {
      label: '出/入库单价',
      value: 'settlementPrice',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '订单数量',
      value: 'orderCalcQty',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '可开票数量',
      value: 'availableQty',
      formatter: proxy.$fn.qtyFormatter,
    },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    ...props.query,
    sort: 'create_time desc',
  },
  btnList: [{ type: 'slot', value: 'btn' }],
})
// 表格相关
const tableInfo = ref({
  api: null,
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    { label: '结算单号', value: 'businessOrderNo' },
    { label: '产品名称', value: 'commonName' },
    { label: '批号', value: 'batchNumber' },
    { label: '产品类型', value: 'productTypeValue' },
    {
      label: '订单数量',
      value: 'orderCalcQty',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '可开票数量',
      value: 'availableQty',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '出/入库单价',
      value: 'exportStorePrice',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '开票单价',
      value: 'price',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '开票数量',
      value: 'calcQty',
      type: 'slot',
      width: 148,
    },
    {
      label: '开票金额',
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
})
// 弹窗相关
const dialogInfo = ref({
  title: '产品明细操作',
  btLoading: false,
  width: '90%',
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      disabled: true,
      event: save,
      show: true,
    },
  ],
})
const selectRow = ref('')
const shows = computed({
  get() {
    return props.showDialog
  },
  set(val) {
    proxy.$emit('update:showDialog', val)
  },
})
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val && val.length) {
      // let ids = []
      // val.forEach((item) => {
      //   if (item.pendReceiptId) {
      //     ids.push(item.pendReceiptId)
      //   } else {
      //     ids.push(item.id)
      //   }
      // })
      // leftFilterInfo.value.query.idNotIn = String(ids)
      dialogInfo.value.btList[1].disabled = false
    } else {
      // leftFilterInfo.value.query.idNotIn = ''
      dialogInfo.value.btList[1].disabled = true
    }
  },
  { deep: true }
)
function removeLeft() {
  //左移
  tableInfo.value.data = tableInfo.value.data.filter(
    (row) => !tableInfo.value.selections.includes(row)
  )
  if (tableInfo.value.data.length) {
    let ids = tableInfo.value.data.map((item) => {
      if (item.pendReceiptId) {
        return item.pendReceiptId
      } else {
        return item.id
      }
    })
    leftFilterInfo.value.query.idNotIn = ids.toString()
  } else {
    leftFilterInfo.value.query.idNotIn = ''
  }

  tableInfo.value.selections = []
  proxy.$refs['productTable'].clearSelection()
  proxy.$refs['table'].clearSelection()
  getLeftList()
}
function removeRight() {
  //右移
  leftTableInfo.value.data = leftTableInfo.value.data.filter(
    (row) => !leftTableInfo.value.selections.includes(row)
  )
  leftTableInfo.value.selections.forEach((item) => {
    item['price'] = props.selectData.price
    item['calcQty'] = item.availableQty
    item['sumAmount'] = proxy.$fn.accMul(
      item.availableQty || 0,
      props.selectData.price
    )
    item['businessOrderNo'] = item.orderNo
    item['businessOrderType'] = item.orderType
    item['exportStorePrice'] = item.settlementPrice
    tableInfo.value.data.push(item)
  })
  if (tableInfo.value.data.length) {
    let ids = tableInfo.value.data.map((item) => {
      if (item.pendReceiptId) {
        return item.pendReceiptId
      } else {
        return item.id
      }
    })
    leftFilterInfo.value.query.idNotIn = ids.toString()
  } else {
    leftFilterInfo.value.query.idNotIn = ''
  }
  proxy.$refs['productTable'].clearSelection()
  proxy.$refs['table'].clearSelection()
  leftTableInfo.value.selections = []
  getLeftList()
}
function changeNum(e, row, str) {
  let sumAmount = 0
  if (str === 'price') {
    sumAmount = proxy.$fn.accMul(e, row.calcQty || 0)
  } else if (str === 'calcQty') {
    sumAmount = proxy.$fn.accMul(e, row.price || 0)
  }
  row['sumAmount'] = sumAmount
}
// 获取列表
function getList() {
  tableInfo.value.data = props.selectData.extDetails
}
function getLeftList() {
  console.log(leftTableInfo.value, 'leftTableInfo.value')
  leftTableInfo.value.api = props.api
  leftTableInfo.value.refresh = Math.random()
}
function search() {
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function setQty(data) {
  let calcQty = 0
  let sumAmount = 0
  data.forEach((item) => {
    let qty = item.calcQty || 0
    calcQty = proxy.$fn.accAdd(calcQty, qty)
    let sum = item.sumAmount || 0
    sumAmount = proxy.$fn.accAdd(sumAmount, sum)
  })
  return {
    calcQty: calcQty,
    sumAmount: sumAmount,
  }
}
function save() {
  if (tableInfo.value.data && tableInfo.value.data.length) {
    //校验数量：开票数量必须大于0
    let calcQtyArr = []
    tableInfo.value.data.forEach((item) => {
      if (!item.calcQty) {
        calcQtyArr.push(item)
      }
    })
    if (calcQtyArr && calcQtyArr.length) {
      proxy.$message.warning('开票数量必填且大于0!')
      return
    }
    let obj = setQty(tableInfo.value.data)
    tableInfo.value.data.forEach((item) => {
      if (!item.pendReceiptId) {
        item.pendReceiptId = item.id
      }
      if (!item.exportStorePrice) {
        item.exportStorePrice = item.settlementPrice
      }
    })
    console.log(tableInfo.value.data, 'tableInfo.value.data')
    handleClose()
    proxy.$emit('callback', tableInfo.value.data, obj)
  } else {
    proxy.$message({
      type: 'warning',
      duration: 3500,
      showClose: true,
      message: '请选择产品',
    })
  }
}
function leftHandleEvent(event, data) {
  const tableInfo = leftTableInfo.value
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = data
      break
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableClickRow':
      selectRow.value = data
      break
    case 'tableCheck':
      selectRow.value = data
      tableInfo.value.selections = data
      break
  }
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  proxy.$emit('reset')
}
onMounted(() => {
  // hack, 在table创建出来之后再去调用
  proxy.$nextTick(() => {
    getList()
    getLeftList()
  })
})
</script>

<style scoped></style>
